//
//  TMGMakeOrderViewController.m
//  TMGold
//
//  Created by Mac on 2018/3/24.
//  Copyright © 2018年 tangmu. All rights reserved.
//

#import "TMGMakeOrderViewController.h"
#import "NSCalendar+STCalendarTool.h"
#import "UITableView+STNoresult.h"
#import "TMGChoseDisCountViewController.h"
@interface TMGMakeOrderViewController ()
@property(nonatomic, strong) NSArray                     *dataSouce;
@property(nonatomic, strong) TMGDiscountModel                     *chosedModel;/**< 优惠券model */
@end

@implementation TMGMakeOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"提交订单";
    [self configDataSouce];
     [self confimBootomView];
    // Do any additional setup after loading the view.
}
- (void)configDataSouce{
    
    NSString * name = self.model.name;
    NSString * value;
    if (self.ke.length) {
       value = [NSString stringWithFormat:@"%0.2f克",
                self.ke.floatValue];
    }else{
        value = [NSString stringWithFormat:@"%@元",self.money];
    }
    
    NSDate * date = [NSDate st_localCurrentDate];
    

    
    if (self.model.cate.integerValue > 3) {
        self.dataSouce = @[
                           [[STTableEasyModel alloc] initWithTextString:name detailString:value],
                           [[STTableEasyModel alloc] initWithTextString:@"订单总额"
                                                           detailString:[NSString stringWithFormat:@"%@元",self.money]],
                           [[STTableEasyModel alloc] initWithTextString:@"计息日" detailString:[NSCalendar st_nextDayDate:date].st_yyyyMMddByLineWithDate]
                           ];
    }else{
        self.dataSouce = @[
                           [[STTableEasyModel alloc] initWithTextString:name detailString:value],
                           [[STTableEasyModel alloc] initWithTextString:@"订单总额"
                                                           detailString:[NSString stringWithFormat:@"%@元",self.money]],
                           [[STTableEasyModel alloc] initWithTextString:@"当前黄金价格" detailString:@""],
                           [[STTableEasyModel alloc] initWithTextString:@"计息日" detailString:[NSCalendar st_nextDayDate:date].st_yyyyMMddByLineWithDate]
                           ];
        if (self.model.cate.integerValue == 1) {
            STTableEasyModel * model = self.dataSouce[2];
            model.textString = @"活动黄金价格";
            model.detailString = [NSString stringWithFormat:@"%@元/克",@"248"];
            [self.tableView reloadData];
        }else{
            [TMUtils fetchCurrentGoldPrice:^(TMCurrentColdModel *currentModel) {
                NSString * goldmoney = currentModel.latestpri;
                STTableEasyModel * model = self.dataSouce[2];
                model.detailString = [NSString stringWithFormat:@"%@元/克",goldmoney];
                [self.tableView reloadData];
                
            }];
        }

    }
    

    [self.tableView reloadData];
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSouce.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 44;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.01;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuseIdentifier];
        
    }
    STTableEasyModel * mdoel = self.dataSouce[indexPath.row];
    cell.textLabel.textColor = UIColorFromRGBA(0x333333);
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    cell.detailTextLabel.font = [UIFont systemFontOfSize:13];
    cell.detailTextLabel.textColor = UIColorFromRGBA(0x333333);

    cell.textLabel.text = mdoel.textString;
    cell.detailTextLabel.text = mdoel.detailString;
    cell.accessoryType = UITableViewCellAccessoryNone;
    
    return cell;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}

#pragma mark --subView

- (void)confimBootomView{
    CGFloat top = [TMUtils tabBarTop];
    __weak typeof(self) weakSelf =  self;
    STButton * buyButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 100, 49)
                                                     title:@"确定下单"
                                                titleColor:[UIColor whiteColor]
                                                 titleFont:18
                                              cornerRadius:0
                                           backgroundColor:TM_orangeColor
                                           backgroundImage:nil
                                                     image:nil];
    buyButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [buyButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelctedBuyButton];
    }];
    buyButton.top = top;
    buyButton.right = UIScreenWidth;
    [self.view addSubview:buyButton];
    
    STLabel * titleLable = [[STLabel alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth - 100, 49)
                                                     text:[NSString stringWithFormat:@"   在线支付:  ￥%@",self.money]
                                                textColor:TM_orangeColor
                                                     font:14
                                              isSizetoFit:NO
                                            textAlignment:NSTextAlignmentLeft];
    titleLable.top = top;
    titleLable.backgroundColor = [UIColor whiteColor];
    titleLable.attributedText = [titleLable.text st_convertAttributeStringWithKeyWord:@"在线支付:" attributes:@{NSForegroundColorAttributeName:FirstTextColor}];
    [self.view addSubview:titleLable];
}
#pragma mark --Action Method
- (void)onSelctedBuyButton{
    self.chosedModel = nil;
    if (![STUserManger defult].loginUser.bank_card.length) {
        [SVProgressHUD showErrorWithStatus:@"请先绑定银行卡在进行购买"];
    }else{
        [self judgeIsExistDisCount];

    }
    
}
#pragma mark --NetWork Method
- (void)sendCreateOrderRequest{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@",service_header,@"/gold/public/api/order/addOrderBuy"];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    if ([STUserManger defult].token.length) {
        [dic setObject:[STUserManger defult].token forKey:@"token"];
    }
    [dic setObject:self.model.goodID forKey:@"gid"];
    [dic setObject:self.model.cate forKey:@"cate"];
    [dic setObject:self.model.year_rate_from forKey:@"year_rate"];
    [dic setObject:self.trade_type forKey:@"trade_type"];
    NSDate * date = [NSDate st_localCurrentDate];
    NSString * today = date.st_yyyyMMddByLineWithDate;
    [dic setObject:today forKey:@"start"];
    for (NSInteger i =0; i < 90; i ++ ) {
        date = [NSCalendar st_nextDayDate:date];
    }
    if (self.ke.length) {
        [dic setObject:self.ke forKey:@"goods_number"];
    }else{
        [dic setObject:self.money forKey:@"goods_number"];
    }

    if (self.end.length) {
       [dic setObject:self.end forKey:@"end"];
    }
    
    if (self.m_vid.length) {
        [dic setObject:self.m_vid forKey:@"m_vid"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 
                                                 //                                                 [SVProgressHUD showSuccessWithStatus:@"下单成功"];
                                                 NSNumber * oid =responseObject[@"data"][@"oid"];
                                                 [TMUtils fetchPersonnalInfo:^(TMGUserModel *user) {
                                                     [SVProgressHUD dismiss];
                                                     if (user.is_verify) {
                                                        
                                                         [self presentInputPwdViewControllerWithOrder:oid.description];
                                                     }else{
                                                         [SVProgressHUD showErrorWithStatus:@"请先实名认证"];
                                                     }
                                                 }];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
- (void)judgeIsExistDisCount{
    [SVProgressHUD showWithStatus:@"请稍后"];
    STTableEasyModel * model = self.dataSouce.firstObject;
    NSString * title = model.textString;
    NSString * money = self.money;
    [self sendCreateOrderRequest];
    return;
    [TMUtils fecthOnSaleRequestWithGoodTitle:title money:money handle:^(NSArray *array) {
        [SVProgressHUD dismiss];
        if (!array.count) {
            [self sendCreateOrderRequest];
        }else{
            [self showAlertTitle:@"检测到您还有未使用的优惠券，请问需要使用吗" message:@"" leftTitle:@"不了" rightTitle:@"去选择" block:^(NSString *name) {
                if ([name isEqualToString:@"去选择"]) {
                    TMGChoseDisCountViewController * discountVC  = [TMGChoseDisCountViewController new];
                    discountVC.dataSouce = array;
                    [discountVC setChosedHandle:^(TMGDiscountModel *model) {
                        if (model) {
                            self.chosedModel = model;
                            [self sendCreateOrderRequest];
                        }else{
                          [self sendCreateOrderRequest];
                        }
                        
                    }];
                    [self.navigationController pushViewController:discountVC animated:YES];
                }else{
                   [self sendCreateOrderRequest];
                }
                
            }];
        }
    }];
}
- (void)presentInputPwdViewControllerWithOrder:(NSString*)order{
    LBPassWordPresentViewController * vc = [LBPassWordPresentViewController new];
    [vc setPwdDidEdited:^(LBPassWordPresentViewController *passVC ,NSString *inputPwd) {
        [self sendBuyRequestWithOid:order pwd:inputPwd handle:^(NSString *errorDesc) {
            if (!errorDesc.length) {
                [SVProgressHUD showSuccessWithStatus:@"购买成功"];
                [passVC dismissWithHandle:^{
                    [self.navigationController popViewControllerAnimated:YES];
                }];
            }else{
                if ([errorDesc isEqualToString:@"交易密码不正确!"]) {
                    passVC.alertLable.text = @"密码错误";
                    passVC.alertLable.hidden = NO;
                    [passVC rightLablebackAnimation];
                }else{
                    [SVProgressHUD showErrorWithStatus:errorDesc];
                }
                
            }
        }];
    }];
    [self presentViewController:vc animated:NO completion:nil];
}
- (void)sendBuyRequestWithOid:(NSString*)oid pwd:(NSString*)pwd handle:(void(^)(NSString * errorDesc))handle{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@",service_header,@"/gold/public/api/money/balancePay"];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    if ([STUserManger defult].token.length) {
        [dic setObject:[STUserManger defult].token forKey:@"token"];
    }
    if (oid.length) {
        [dic setObject:oid forKey:@"oid"];
    }
    if (pwd.length) {
        [dic setObject:pwd forKey:@"pay_password"];
    }

    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 if (handle) {
                                                     handle(@"");
                                                 }
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 if (handle) {
                                                     handle(error.desc);
                                                 }
                                             }];
}

@end
